package com.alibaba.citrus.ots.platform.enhance.facade.service.scitem;

import javax.annotation.Resource;

import com.alibaba.citrus.ots.platform.enhance.functions.item.ScItemEntity;
import com.alibaba.citrus.ots.platform.enhance.repository.ScItemRepository;
import com.alibaba.cz.base.tool.MapUtil;
import com.alibaba.cz.base.tool.Nullable;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.page.PageResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;

import com.epoch.app.bcots.model.dto.CategoryGetCurrentCategoryByIdRequest;
import com.epoch.app.bcots.model.dto.ScItemExtendSDO;
import com.epoch.app.bcots.model.dto.SearchScItemRequest;
import com.epoch.app.bcots.service.BaseDataService;
import com.epoch.app.bcots.service.BcOtsService;
import com.epoch.app.otsplatformenhance.api.scitemquery.service.ScItemQueryService;
import com.epoch.app.otsplatformenhance.dto.request.BaselineQueryScItemByPageRequest;
import com.epoch.app.otsplatformenhance.dto.request.IdQueryRequest;
import com.epoch.app.otsplatformenhance.dto.request.QueryScItemRequest;
import com.epoch.app.otsplatformenhance.dto.response.QueryGoodsListResponse;
import com.epoch.app.otsplatformenhance.model.dto.ScItemSDO;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.TreeSet;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

/**
 * @author zls
 * @description: TODO
 * @date 2021/9/7 15:30
 */
@Primary
@Service
public class ScItemQueryServiceImpl implements ScItemQueryService {

    Log log = Log.getLogger(ScItemQueryServiceImpl.class);

    @Resource
    ScItemRepository scItemRepository;

    @Resource
    BaseDataService baseDataService;

    @Resource
    BcOtsService bcOtsService;


    @Resource(name = "scItemsQueryTaskExecutor")
    private ThreadPoolTaskExecutor scItemsQueryTaskExecutor;

    @Override
    public Result<ScItemSDO> getScItemById(IdQueryRequest request) {
        System.out.println("入参==" + request);
        ScItemSDO scItemSDO = new ScItemSDO();
        scItemSDO.setScItemId(request.getId());
        ScItemEntity scItemEntity = ScItemEntity.of(scItemSDO);
        //  记得把feature拿出来 todo    9.16  放上层  rainbow
        return Result.success(scItemEntity.doQueryById());
    }

    @Override
    public Result<List<ScItemSDO>> pageQueryScItemList(QueryScItemRequest request) {
        PageResult<List<ScItemSDO>> pageResult = scItemRepository.pageQueryScItemList(request);
        return Result.listSuccess(pageResult.getContent(), pageResult.getTotal());
    }

    @Override
    public Result<List<ScItemSDO>> pageQueryScItemListFromDB(QueryScItemRequest request) {
        PageResult<List<ScItemSDO>> pageResult = scItemRepository.pageQueryScItemListFromDB(request);
        return Result.listSuccess(pageResult.getContent(), pageResult.getTotal());
    }

    /**
     * 定制化接口，查询货品并按类目分组
     *
     * @param baselineQueryScItemByPageRequest
     * @return
     */
    @Override
    public Result<List<QueryGoodsListResponse>> queryGoodsList(BaselineQueryScItemByPageRequest baselineQueryScItemByPageRequest) {
        List outIdList = baselineQueryScItemByPageRequest.getOutIdList();
        // outerId支持模糊搜索
        String outerIdReq = "";
        if (!CollectionUtils.isEmpty(outIdList) && outIdList.size() == 1) {
            outerIdReq = outIdList.get(0).toString();
        }
        List<QueryGoodsListResponse> responseList = new ArrayList<>();

        List<com.epoch.app.bcots.model.dto.ScItemSDO> scItemSDOListAll = Lists.newArrayList();
        List<Future<List<com.epoch.app.bcots.model.dto.ScItemSDO>>> futureList = Lists.newArrayList();
        int totalCnt = baselineQueryScItemByPageRequest.getLimit();
        for (int i = 1; i <= totalCnt / 10; i++) {
            int finalI = i;
            String finalOuterIdReq = outerIdReq;
            CompletableFuture<List<com.epoch.app.bcots.model.dto.ScItemSDO>> future = CompletableFuture.supplyAsync(() -> {
                Result<List<com.epoch.app.bcots.model.dto.ScItemSDO>> searchScItemResult = null;
                try {
                    // 构造查询参数
                    SearchScItemRequest searchScItemRequest = new SearchScItemRequest();
                    searchScItemRequest.setPageNum(baselineQueryScItemByPageRequest.getPage());
                    searchScItemRequest.setPageSize(baselineQueryScItemByPageRequest.getLimit());
                    Map searchReqDTO = new HashMap();
                    if (StringUtils.isNotBlank(finalOuterIdReq)) {
                        searchReqDTO.put("outerId", finalOuterIdReq);
                    } else {
                        searchReqDTO.put("outerIdList", baselineQueryScItemByPageRequest.getOutIdList());
                    }
                    searchReqDTO.put("scItemIds", baselineQueryScItemByPageRequest.getIdList());
                    searchReqDTO.put("title", baselineQueryScItemByPageRequest.getTitle());
                    searchScItemRequest.setSearchReqDTO(searchReqDTO);
                    searchScItemRequest.setPageSize(10);
                    searchScItemRequest.setPageNum(finalI);
//                    log.info("分片查询参数{}", JSON.toJSONString(searchScItemRequest));
                    searchScItemResult = baseDataService.searchScItem(searchScItemRequest);
                } catch (Exception e) {
                    log.error("多线程查询货品异常", e);
                }

//                log.info("多线程查询货品结果{}", JSON.toJSONString(searchScItemResult));
                if (null == searchScItemResult) {
                    return null;
                }
                boolean success = searchScItemResult.isSuccess();
                if (!success) {
                    return null;
                }
                List<com.epoch.app.bcots.model.dto.ScItemSDO> scItemSDOSubList = searchScItemResult.getResult();
                return scItemSDOSubList;
            }, scItemsQueryTaskExecutor);
            futureList.add(future);
        }

        for (Future<List<com.epoch.app.bcots.model.dto.ScItemSDO>> listFuture : futureList) {
            try {
                List<com.epoch.app.bcots.model.dto.ScItemSDO> subList = listFuture.get();
                scItemSDOListAll.addAll(Optional.ofNullable(subList).orElse(Lists.newArrayList()));
            } catch (Exception e) {
                // 异常处理
                log.error("获取多线程查询结果异常", e);

            }
        }

        List<com.epoch.app.bcots.model.dto.ScItemSDO> scItemList = Lists.newArrayList();
        Map<String, com.epoch.app.bcots.model.dto.ScItemSDO> scItemMap = Maps.newHashMap();
        Map<String, Map> categoryMap = Maps.newHashMap();
        for (com.epoch.app.bcots.model.dto.ScItemSDO scItemSDO : scItemSDOListAll) {
            if (scItemSDO == null || StringUtils.isBlank(scItemSDO.getOuterId())) {
                continue;
            }

            if (scItemMap.containsKey(scItemSDO.getOuterId())) {
                continue;
            }

            scItemList.add(scItemSDO);
            scItemMap.put(scItemSDO.getOuterId(), scItemSDO);

            // 获取类目
            String leafCategoryId = scItemSDO.getLeafCategoryId();
            if (StringUtils.isNotBlank(leafCategoryId) && !categoryMap.containsKey(leafCategoryId)) {
                try {
                    CategoryGetCurrentCategoryByIdRequest categoryGetCurrentCategoryByIdRequest = new CategoryGetCurrentCategoryByIdRequest();
                    categoryGetCurrentCategoryByIdRequest.setId(leafCategoryId);
                    Map tmpCategoryMap = (Map) bcOtsService.categoryGetCurrentCategoryById(categoryGetCurrentCategoryByIdRequest);
                    if (tmpCategoryMap != null && tmpCategoryMap.get("result") != null) {
                        categoryMap.put(leafCategoryId, (Map) tmpCategoryMap.get("result"));
                    }

                } catch (Exception e) {
                    log.error("获取类目信息失败", e);
                }
            }

        }

        // 先遍历所有货品，查询一级类目下的parentCategoryId，塞到一个sdo里面，然后根据parentCategoryId分组
        List<ScItemExtendSDO> scItemExtendSDOList = new ArrayList<>();
        for (com.epoch.app.bcots.model.dto.ScItemSDO scItemSDO : scItemList) {
            ScItemExtendSDO scItemExtendSDO = new ScItemExtendSDO();
            BeanUtils.copyProperties(scItemSDO, scItemExtendSDO);
            String leafCategoryId = scItemSDO.getLeafCategoryId();
            if (StringUtils.isNotBlank(leafCategoryId)) {
                Map categoryResultMap = categoryMap.get(leafCategoryId);
                if (MapUtils.isNotEmpty(categoryResultMap)) {
                    String parentCategoryId = categoryResultMap.get("parentId").toString();
                    Object path = categoryResultMap.get("path");
                    List<String> pathList = JSONObject.parseArray(JSON.toJSONString(path), String.class);
                    String parentCategoryName = "";
                    if (!CollectionUtils.isEmpty(pathList) && pathList.size() < 2) {
                        parentCategoryName = pathList.get(0);
                        parentCategoryId = leafCategoryId;
                    } else if (!CollectionUtils.isEmpty(pathList) && pathList.size() == 2) {
                        parentCategoryName = pathList.get(1);
                        parentCategoryId = leafCategoryId;

                    } else if (!CollectionUtils.isEmpty(pathList) && pathList.size() > 2) {
                        parentCategoryName = pathList.get(1);
                    }
                    String currentPath = categoryResultMap.get("currentPath").toString();
                    String rootId = categoryResultMap.get("rootId").toString();
                    String parentId = categoryResultMap.get("parentId").toString();
                    String catId = categoryResultMap.get("catId").toString();
                    String idPath;
                    if (rootId.equals(parentId)) {
                        idPath = rootId + ">>" + catId;
                    } else {
                        idPath = rootId + ">>" + parentId + ">>" + catId;
                    }
                    scItemExtendSDO.setParentCategoryId(parentCategoryId);
                    scItemExtendSDO.setParentCategoryName(parentCategoryName);
                    scItemExtendSDO.setCurrentPath(currentPath);
                    scItemExtendSDO.setIdPath(idPath);
                }
            }
            scItemExtendSDOList.add(scItemExtendSDO);
        }
        // 常用货品配置
        String titleReq = baselineQueryScItemByPageRequest.getTitle();
        List<ScItemExtendSDO> scItemExtendSDORecentlyList = new ArrayList<>();
        List<String> recentlyUsedItemIdList = Lists.newArrayList();
        List<String> oriRecentlyUsedItemIdList = Optional.ofNullable(baselineQueryScItemByPageRequest.getRecentlyUsedItemIdList()).orElse(Lists.newArrayList());
        for (String s : oriRecentlyUsedItemIdList) {
            if (StringUtils.isNotBlank(s) && !recentlyUsedItemIdList.contains(s) && !"null".equalsIgnoreCase(s)) {
                recentlyUsedItemIdList.add(s);
            }
        }

        if (Objects.nonNull(recentlyUsedItemIdList)) {
            List outIdListNew = baselineQueryScItemByPageRequest.getOutIdList();
            if (!CollectionUtils.isEmpty(outIdListNew)) {
                boolean disjoint = Collections.disjoint(outIdListNew, recentlyUsedItemIdList);
                if (disjoint) {
                    recentlyUsedItemIdList = Lists.newArrayList();
                } else {
                    recentlyUsedItemIdList = outIdList;
                }
            }
            if (!CollectionUtils.isEmpty(recentlyUsedItemIdList)) {
                List<com.epoch.app.bcots.model.dto.ScItemSDO> listResult = Lists.newArrayList();
                for (String s : recentlyUsedItemIdList) {
                    com.epoch.app.bcots.model.dto.ScItemSDO scItem = scItemMap.get(s);
                    if (scItem != null) {
                        listResult.add(scItem);
                    }
                }

                List<ScItemExtendSDO> tmpScItemExtendSDORecentlyList = listResult.stream().map(scItemSDO -> {
                    ScItemExtendSDO scItemExtendSDO = new ScItemExtendSDO();
                    BeanUtils.copyProperties(scItemSDO, scItemExtendSDO);
                    scItemExtendSDO.setParentCategoryId("99999999");
                    scItemExtendSDO.setParentCategoryName("近期使用");
                    return scItemExtendSDO;
                }).collect(Collectors.toList());

                // 按照原始的添加顺序排序
                Map<String, List<ScItemExtendSDO>> recentlyUsedItemMap = Optional.ofNullable(tmpScItemExtendSDORecentlyList).orElse(Lists.newArrayList()).stream().collect(Collectors.groupingBy(ScItemExtendSDO::getOuterId));
                for (String s : recentlyUsedItemIdList) {
                    if (MapUtils.isNotEmpty(recentlyUsedItemMap) && !CollectionUtils.isEmpty(recentlyUsedItemMap.get(s))) {
                        scItemExtendSDORecentlyList.add(recentlyUsedItemMap.get(s).get(0));
                    }
                }

            }
        }
        scItemExtendSDOList.addAll(scItemExtendSDORecentlyList);
        //增加货品收藏夹类目
        List<String> goodsFavoritesList = baselineQueryScItemByPageRequest.getGoodsFavoritesList();
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(goodsFavoritesList)){
            goodsFavoritesList=goodsFavoritesList.stream().distinct().collect(Collectors.toList());
            List<ScItemExtendSDO> scItemGoodsFavoritesList = new ArrayList<>();
            List<com.epoch.app.bcots.model.dto.ScItemSDO> favoritesGoodsIdList = Lists.newArrayList();
            for (String s : goodsFavoritesList) {
                com.epoch.app.bcots.model.dto.ScItemSDO scItem = scItemMap.get(s);
                if (scItem != null) {
                    favoritesGoodsIdList.add(scItem);
                }
            }
            List<ScItemExtendSDO> tmpGoodsFavoritesList = Nullable.stream(favoritesGoodsIdList).map(scItemSDO -> {
                ScItemExtendSDO scItemExtendSDO = new ScItemExtendSDO();
                BeanUtils.copyProperties(scItemSDO, scItemExtendSDO);
                scItemExtendSDO.setParentCategoryId("88888888");
                scItemExtendSDO.setParentCategoryName("收藏夹");
                return scItemExtendSDO;
            }).collect(Collectors.toList());


            Map<String, List<ScItemExtendSDO>> favoritesItemMap = Optional.ofNullable(tmpGoodsFavoritesList).orElse(Lists.newArrayList()).stream().collect(Collectors.groupingBy(ScItemExtendSDO::getOuterId));
            for (String s : goodsFavoritesList) {
                if (MapUtils.isNotEmpty(favoritesItemMap) && !CollectionUtils.isEmpty(favoritesItemMap.get(s))) {
                    scItemGoodsFavoritesList.add(favoritesItemMap.get(s).get(0));
                }
            }
            scItemExtendSDOList.addAll(scItemGoodsFavoritesList);
        }


        //根据父级类目id分组，支持类目为空
        Map<Optional<String>, List<ScItemExtendSDO>> collectMap = scItemExtendSDOList.stream().collect(Collectors.groupingBy(x -> Optional.ofNullable(x.getParentCategoryId())));
        // 遍历分组
        for (Optional<String> key : collectMap.keySet()) {
            QueryGoodsListResponse queryGoodsListResponse = new QueryGoodsListResponse();
            // 没有类目的默认类目id为0，名称叫”未分类的“
            if (!key.isPresent()) {
                continue;
//                queryGoodsListResponse.setValue("0");
//                queryGoodsListResponse.setLabel("未分类的");
            } else {
                List<ScItemExtendSDO> scItemExtendSDOList1 = collectMap.get(key);
                if (CollectionUtils.isEmpty(scItemExtendSDOList1)) {
                    continue;
                }
                queryGoodsListResponse.setValue(key.get());
                ScItemExtendSDO scItemExtendSDO = collectMap.get(key).get(0);
                queryGoodsListResponse.setLabel(scItemExtendSDO.getParentCategoryName());
            }
            List<Map> resultMapList = new ArrayList<>();
            // 遍历每组的列表
            List<ScItemExtendSDO> scItemExtendSDOListNew = collectMap.get(key);
            if (CollectionUtils.isEmpty(scItemExtendSDOListNew)) {
                continue;
            }
            for (ScItemExtendSDO scItemSDO : scItemExtendSDOListNew) {
                String currentPath = scItemSDO.getCurrentPath();
                String idPath = scItemSDO.getIdPath();
                Map scItemSDOMap = new HashMap();
                String title = scItemSDO.getTitle();
                String scItemId = scItemSDO.getScItemId();
                String outerId = scItemSDO.getOuterId();
                String unit = scItemSDO.getUnit();
                Map<String, String> features = scItemSDO.getFeatures();
                scItemSDOMap.put("goodsCode", outerId);
                scItemSDOMap.put("id", scItemId);
                scItemSDOMap.put("goodsName", title);
                scItemSDOMap.put("baseUnitCode", features.get("unitName"));
                scItemSDOMap.put("baseUnitName", unit);
                // 类目名称路径
                if (StringUtils.isNotBlank(currentPath)) {
                    scItemSDOMap.put("currentPath", currentPath);
                }
                // 类目ID路径
                if (StringUtils.isNotBlank(idPath)) {
                    scItemSDOMap.put("idPath", idPath);
                }
                // 品类划分编码
                String category = features.get("category");
                if (StringUtils.isNotBlank(category)) {
                    scItemSDOMap.put("category", category);
                }
                // 品类划分描述
                String categoryDesc = features.get("categoryDesc");
                if (StringUtils.isNotBlank(categoryDesc)) {
                    scItemSDOMap.put("categoryDesc", categoryDesc);
                }
                // 品项编码
                String categoryChildCode = features.get("categoryChildCode");
                if (StringUtils.isNotBlank(categoryChildCode)) {
                    scItemSDOMap.put("categoryChildCode", categoryChildCode);
                }
                // 品项编码描述
                String categoryChildDesc = features.get("categoryChildDesc");
                if (StringUtils.isNotBlank(categoryChildDesc)) {
                    scItemSDOMap.put("categoryChildDesc", categoryChildDesc);
                }
                String guaranteePeriod = features.get("guaranteePeriod");
                if (StringUtils.isNotBlank(guaranteePeriod)) {
                    scItemSDOMap.put("guaranteePeriod", guaranteePeriod);
                }
                resultMapList.add(scItemSDOMap);
            }
            queryGoodsListResponse.setGoodsList(resultMapList);
            responseList.add(queryGoodsListResponse);
        }
        // 将近期使用分组放到第二个
        List<QueryGoodsListResponse> collectRecent = responseList.stream()
                .filter(queryGoodsListResponse -> "99999999".equals(queryGoodsListResponse.getValue())).collect(Collectors.toList());

        // 将收藏夹分组放到第一个
        List<QueryGoodsListResponse> collectFavorites = responseList.stream()
                .filter(queryGoodsListResponse -> "88888888".equals(queryGoodsListResponse.getValue())).collect(Collectors.toList());


        List<QueryGoodsListResponse> collect = responseList.stream()
                .filter(queryGoodsListResponse -> !"99999999".equals(queryGoodsListResponse.getValue()) && !"88888888".equals(queryGoodsListResponse.getValue()))
                .sorted(Comparator.comparing(QueryGoodsListResponse::getValue)).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(collectRecent)) {
            collect.add(0, collectRecent.get(0));
        }else {
            collect.add(0, new QueryGoodsListResponse(){{
                setLabel("近期使用");
                setValue("99999999");
                setGoodsList(Lists.newArrayList());
            }});
        }

        if (!CollectionUtils.isEmpty(collectFavorites)) {
            collect.add(0, collectFavorites.get(0));
        }else {
            collect.add(0, new QueryGoodsListResponse(){{
                setLabel("收藏夹");
                setValue("88888888");
                setGoodsList(Lists.newArrayList());
            }});
        }
        return Result.listSuccess(collect, collect.size());
    }

    public static void main(String[] args) {
        List<String> list1 = null;
        List<String> list2 = Lists.newArrayList("1111");
        boolean disjoint1 = Collections.disjoint(list1, list2);
        boolean disjoint2 = Collections.disjoint(list2, list1);
        System.out.println(disjoint1);
        System.out.println(disjoint2);
    }
}
